import request from "../request.js"
import cfg from "../config.js"

//修改默认请求格式与后台匹配
function requestAdaptor(api, ignores) {
  let data = api.data;
  api.data = {
    filter: []
  }
  let keys = Object.keys(data);
  for (let key of keys) {
    if (key == 'page') {
      api.data.page = data.page;
    }
    else if (key == 'perPage') {
      api.data.perpage = data.perPage;
    }
    else if (key == 'orderBy') {
      api.data.orderby = data.orderBy;
    }
    else if (key == 'orderDir') {
      api.data.orderdir = data.orderDir;
    }
    else if (key == 'keywords') {
      api.data.keywords = data.keywords;
    }
    else {
      api.data.filter.push({
        key: key,
        value: data[key],
        like: true
      })
    }
  }
  return api;
}

let page_type = {
  open: function (page_info) {
    let page_html_id=page_info.page_html_id;
    let property=page_info.property;
    let ext_js=page_info.ext_js;
    let page_id=page_info.page_id;
    let rights=page_info.rights;
    let params=page_info.params;
    let datamodel = property.datamodel;
    let perpage = property.perpage ? property.perpage : 10;
    if(params && params.default_filter) property.default_filter=params.default_filter;
    let path = "datamodel/getinfo";
    request(path, { datamodel: datamodel }, function (info) {
      let tablename = info.tablename;
      let modelname = info.modelname;
      let fields = info.fields;
      let columns = [];
      let keywords_search_columns = [];
      let add_form_controls = [];
      let add_form_controls_group = {};
      for (let field of fields) { //all fields
        if (field.relater) continue; //被关联的字段不显示，源字段显示被关联字段的显示值
        let col = {
          name: field.name,
          label: (field.related && field.related.label) ? field.related.label : field.label
        }
        let keywords_col = {
          name: field.name
        }
        let add_form_control = {
          type: "text",
          name: col.name,
          label: col.label,
          required: field.required
        }
        //系统字段，除ID和创建时间外默认不显示
        if (field.is_sys_field && field.name!="id" && field.name!="create_time") {
          col.toggled=false;
        }
        if (field.is_sys_field){
          col.sortable=true;
        }
        let property_column = property.columns ? property.columns.filter(c => c.name == field.name) : [];
        if (property_column.length > 0) {
          let property = property_column[0];
          col.sortable = property.sortable;
          col.searchable = property.searchable;
          col.toggled = property.toggled;

          if(property.type=="checkbox"){
            col.type="checkbox";
          }
          else if(property.type=="password" || field.type=="password"){
            col.type="tpl";
            col.tpl="****************";
          }
          else if (property.type == "icon") { //图标选择
            col.type = "tpl"
            col.tpl = "<i class='fa ${" + col.name + "}'></i>"
          }
          else if (field.related) { //关联表选择
            col.type = "tpl"
            col.tpl = "<span class='label label-info'>${#" + col.name + "}</span>"
          }
          keywords_col.label_tpl = property.label_tpl;
        }
        columns.push(col);
        keywords_search_columns.push(keywords_col);
      } //// end foreach fields
      //对显示的列进行排序
      columns.sort(function(a,b){
        let a_index=20,b_index=20;
        if(a.name=='id') a_index=0;
        if(b.name=='id') b_index=0;
        if(a.name=='create_time') a_index=21;
        if(b.name=='create_time') b_index=21;
        if(a.name=='create_user') a_index=22;
        if(b.name=='create_user') b_index=22;
        if(a.name=='update_time') a_index=23;
        if(b.name=='update_time') b_index=23;
        if(a.name=='update_user') a_index=24;
        if(b.name=='update_user') b_index=24;
        if(a_index==20 || b_index==20){
          property.columns.forEach(c=>{
            if(a_index==20 && a.name==c.name && b_index!=11) a_index=11;
            if(b_index==20 && b.name==c.name && a_index!=11) b_index=11;
            if(a_index==20 && a.name==c.name && b_index==11) a_index=12;
            if(b_index==20 && b.name==c.name && a_index==11) b_index=12;
          })
        }
        return a_index-b_index;
      });
      
      let amisJSON =
      {
        "cssVars": {
          "--Panel-marginBottom": "0.5rem",
          "--Form-control-widthBase": "20rem"
        },
        "type": "page",
        "name": page_html_id,
        "className": "data-model-edit-page",
        "body": [
          {
            "type": "crud",
            "name": "main_crud_in_" + page_html_id,
            "affixHeader": false,
            "syncLocation": false,
            "perPage": perpage,
            "api": {
              "method": "post",
              "url": cfg.api_server + "datamodel/getrows",
              "requestAdaptor": function (api) {
                let ignores = ['items']
                requestAdaptor(api, ignores);
                api.data.datamodel = datamodel;
                api.data.tablename = tablename;
                if (property.leveled) api.data.leveled = property.leveled;
                api.data.keywords_search_columns = keywords_search_columns;
                //如果查询的字段是关联字段，将字段名前加#，后台根据此判断查询本表还是关联表
                if(api.data.filter){
                  api.data.filter.forEach(f=>{
                    let find_filed=fields.filter(field=>field.name==f.key);
                    if(find_filed.length>0 && find_filed[0].related){
                      f.key="#"+f.key;
                    }
                  })
                }
                keywords_search_columns.forEach(col=>{
                  let find_filed=fields.filter(field=>field.name==col.name);
                  if(find_filed.length>0 && find_filed[0].related){
                    col.name="#"+col.name;
                  }
                })
                //默认的过滤被加到filter中
                if(property.default_filter) api.data.filter=property.default_filter.concat(api.data.filter); 
                //默认的排序，如果没有设置，需要使用默认
                if(!api.data.orderby && property.orderby){
                  api.data.orderby=property.orderby;
                  api.data.orderdir=property.orderdir;
                }
              }
            },
            "keepItemSelectionOnPageChange": true,
            "maxKeepItemSelectionLength": 11,
            "expandConfig": {
              "expand": "all",
              "accordion": false
            },
            "filter": {
              "submitText": "",
              "controls": [
                {
                  "type": "text",
                  "name": "keywords",
                  "placeholder": "通过关键字搜索",
                  "addOn": {
                    "label": "搜索",
                    "type": "submit"
                  }
                },
                {
                  "type": "html",
                  "html": property.tip?"<span class='tip'><i class='fa fa-info-circle'></i> "+property.tip+"</span>":""
                }
              ]
            },
            "filterTogglable": true,
            "headerToolbar": [
              "bulkActions",
              {
                "type": "columns-toggler",
                "align": "right"
              },
              {
                "type": "pagination",
                "align": "right"
              },
              {
                "type": "tpl",
                "tpl": "当前有 ${count} 条数据",
                "className": "v-middle",
                "align": "right"
              }
            ],
            "footerToolbar": [
              "statistics",
              "switch-per-page",
              "pagination"
            ],
            "columns": columns
          }]
      }

      $("#"+page_html_id).addClass("one-select-multi-page row");
      $("#"+page_html_id).html("<div class='col-md-6 col-sm-6 col-xs-12'><div class='main-part'></div></div><div class='col-md-6 col-sm-6 col-xs-12'><div class='tree-part'></div></div>");

      let amis = amisRequire('amis/embed');
      let amisScoped = amis.embed(
        '#' + page_html_id+" .main-part", amisJSON, {},
        {
          theme: 'antd'
        }
      );

      let current_selected_value=null;

      $('#'+page_html_id+" .main-part .antd-Crud").on("click","tbody>tr",function(e){
        $('#'+page_html_id+" .main-part .antd-Crud tbody>tr").removeClass("is-checked ");
        $(this).addClass("is-checked ");
        let row=amisScoped.getComponentByName(page_html_id+".main_crud_in_"+page_html_id).props.data.items[$(this).index()];
        let key=property.r.one_field;
        let value=row[property.r.this_field];
        current_selected_value=value;
        let datamodel=property.r.datamodel;
        let path = "datamodel/getrows";
        request(path, {datamodel:datamodel,filter:[{key:key,value:value,like:false}]}, function (result) {
          let form=treeScoped.getComponentByName(page_html_id+"_m.form_"+page_html_id+"_m");
          let values=[];
          for(let row of result.rows){
            values.push(row[property.r.multi_field]);
          }
          form.setValues({"tree":values.join(",")});
        })
      });

      let treeScoped=undefined;
      let tree_path = "tree/build";
      request(tree_path, {tree:property.r.tree}, function (result) {
        let treeJSON={
          "type": "page",
          "name": page_html_id+"_m",
          "body": {
            "type": "form",
            "name": "form_"+page_html_id+"_m",
            "title": property.r.tip,
            "submitText": "保存",
            "api": {
              "method": "post",
              "url": cfg.api_server + "onemulti/save",
              "requestAdaptor": function (api) {
                api.data.r = property.r;
                api.data.one_value = current_selected_value;
              }
            },
            "body": [
              {
                "type": "input-tree",
                "name": "tree",
                "multiple": true,
                "withChildren": true,
                "initiallyOpen": false,
                "unfoldedLevel": 1,
                "options": result
              }
            ]
          }
        }
        treeScoped = amis.embed(
          '#' + page_html_id+" .tree-part", treeJSON, {},
          {
            theme: 'antd'
          }
        );
      })

    })
  }
}

export default page_type;